package com.lagou.gateway.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Optional;

public class JWTUtil {
    private static Logger LOGGER = LoggerFactory.getLogger(JWTUtil.class);

    public static void main(String[] args) {
        Optional<DecodedJWT> jwtOptional = Optional.ofNullable(
                verify("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImR1eXVkQHFxLmNvbSJ9.eyJhdWQiOiJhbGwiLCJ1aWQiOiJkdXl1ZEBxcS5jb20iLCJzdWIiOiJsYWdvdSIsIm5iZiI6MTU5NTY4OTQzNiwiaXNzIjoibGVlIiwiZXhwIjoxNTk1NjkzMDM2LCJpYXQiOjE1OTU2ODk0MzYsImp0aSI6ImR1eXVkQHFxLmNvbSJ9.FsylHq-rPsY9Z9NI6Hp01nbuHmdENo3phfytvqpZyn0",
                "lee","https://doooyo.github.io"));
        boolean res = jwtOptional.isPresent();

        System.out.println(res);
    }

    public static DecodedJWT verify(String token, String issuer, String secret) {
        LOGGER.info("token: {}\n secret: {}\n issuer: {}", token, secret, issuer);
        DecodedJWT result = null;
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer(issuer)
                    .build();
            DecodedJWT decodedJWT = verifier.verify(token);
            Date expiresAt = decodedJWT.getExpiresAt();
            if (expiresAt.before(new Date())){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                LOGGER.info("已过期, 过期时间: {}", sdf.format(expiresAt));
            }
            result = expiresAt.after(new Date()) ? decodedJWT : null;
        }catch (Exception e){
            LOGGER.error("解签失败: {}", e.getMessage());
        }finally {
            return result;
        }
    }
}
